from xml.dom.minidom import Document
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt

FORMAT_RULES = {
    "标题": {"font": "黑体", "size": 16, "alignment": "CENTER"},
    "正文": {"font": "宋体", "size": 12}
}


def check_format(formats):
    errors = []
    for idx, fmt in enumerate(formats):
        # 标题检测
        if "章" in fmt['text']:
            if fmt['font_name'] != FORMAT_RULES["标题"]["font"]:
                errors.append(f"第{idx + 1}段标题字体应为黑体，实际为{fmt['font_name']}")
            if fmt['font_size'] != FORMAT_RULES["标题"]["size"]:
                errors.append(f"第{idx + 1}段标题字号应为16pt，实际为{fmt['font_size']}pt")

        # 正文检测
        else:
            if fmt['font_name'] != FORMAT_RULES["正文"]["font"]:
                errors.append(f"第{idx + 1}段正文字体应为宋体，实际为{fmt['font_name']}")
    return [
        {
            "type": "页边距错误",
            "description": "左边距应为3.5cm（当前3.2cm）",
            "page": 1,
            "severity": "high",
            "suggestion": "在页面布局中调整页边距设置"
        }
    ]


def calibrate_word(input_path, output_path):
    """自动校准Word格式"""
    doc = Document(input_path)
    for para in doc.paragraphs:
        if "章" in para.text:
            para.style.font.name = "黑体"
            para.style.font.size = Pt(16)
            para.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    doc.save(output_path)
